package com.xiaolin.web.mail;

import java.io.UnsupportedEncodingException;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

/**
 * @ClassName SendEmail
 * @Description TODO
 * @Detail 使用java代码连接邮箱和发送邮件
 *              步骤（以发送人邮箱是QQ邮箱为例）：
 *                  1、编写程序
 *                  2、开启QQ邮箱的POP3/SMTP服务
 *                  3、获取授权码
 * @Author MyPC
 * @Date 2020/9/27
 * @Version 1.0
 */
public class SendEmail {
    public static void main(String[] args) throws UnsupportedEncodingException, MessagingException {
        //发件人邮箱账号
        String from="956704533@qq.com";
        //发送人邮箱密码
        String password="12306pdd9807";
        //发件人邮箱的 SMTP 服务器地址
        String myHost="smtp.qq.com";
        //收件人邮箱账号
        String to="linyuqiang0449@163.com";
        //配置参数，用于连接邮件服务器的参数
        Properties properties = new Properties();
        //使用协议
        properties.setProperty("mail.transport.protocol", "smtp");
        //设置发件人的邮箱服务器地址
        properties.setProperty("mail.smtp.host", myHost);
        //设置需要请求认证
        properties.setProperty("mail.smtp.auth", "true");
        //创建会话对象，用于与邮件服务器交互
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("956704533@qq.com","rmfvgqtuuxcybbdb");
            }
        });
        //创建一封邮件
        MimeMessage mimeMessage = createMimeMessage(session, from, to);
        //根据session获取邮件传输对象
        Transport transport = session.getTransport();
        //使用邮箱和密码连接邮箱服务器
        transport.connect(from,password);
        //发送邮件到目标邮件服务器
        transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
        //关闭连接
        transport.close();

    }

    /**
     * 创建一封简单的邮件
     * @param session 会话对象
     * @param sendMail  发送人邮箱
     * @param receiveMail  收件人邮箱
     * @return
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     */
    public static MimeMessage createMimeMessage(Session session,String sendMail,String receiveMail) throws UnsupportedEncodingException, MessagingException {
        //1、创建一封邮件
        MimeMessage message=new MimeMessage(session);
        //2、设置发件人
        message.setFrom(new InternetAddress(sendMail,"小林","utf-8"));
        //3、设置收件人地址
        Address[] addresses=new Address[1];
        addresses[0]=new InternetAddress(receiveMail);
        message.setRecipients(Message.RecipientType.TO,addresses);
        //4、邮件主题
        message.setSubject("这是一封邮件","utf-8");
        //5、邮件正文
        message.setContent("我是正文","text/html;charset=UTF-8");
        //6、设置发件时间
        message.setSentDate(new Date());
        //7、保存设置
        message.saveChanges();
        return message;
    }
}
